package com.example.royalchef.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.royalchef.R;
import com.example.royalchef.bean.JavascriptInterface;
import com.example.royalchef.bean.SearchInfo;
import com.example.royalchef.utils.UIUtils;
import com.squareup.picasso.Picasso;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * author: Administrator
 * created on: 2017/7/1 9:16
 * description:
 */

public class HomeDetailActivity extends AppCompatActivity {

    @BindView(R.id.tv_home_detail_title)
    TextView tvHomeDetailTitle;

    @BindView(R.id.tv_home_detail_time)
    TextView tvHomeDetailTime;

    @BindView(R.id.iv_home_detail_picture)
    ImageView ivHomeDetailPicture;

    @BindView(R.id.wv_home_detail_introduce)
    WebView wvHomeDetailIntroduce;

    private WebSettings webSettings;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_detail);
        ButterKnife.bind(this);//绑定
        initData();
    }

    private void initData() {
        Intent intent = getIntent();
        SearchInfo searchInfo = intent.getParcelableExtra("searchInfo");
        tvHomeDetailTitle.setText(searchInfo.getTitle());
        tvHomeDetailTime.setText(searchInfo.getCreatedat());
        int width = this.getWindowManager().getDefaultDisplay().getWidth();
        Picasso.with(HomeDetailActivity.this)
                .load(searchInfo.getCover())
                .resize(width, UIUtils.dip2px(100))
                .centerCrop()
                .config(Bitmap.Config.RGB_565)
                .into(ivHomeDetailPicture);

        renderWebView(searchInfo.getContent());
        webSetting();
    }


    private void webSetting() {
        webSettings = wvHomeDetailIntroduce.getSettings();
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setUseWideViewPort(true);//设置webView推荐使用的窗口
        webSettings.setLoadWithOverviewMode(true);//设置webView加载的页面的模式
        webSettings.setDisplayZoomControls(false);//隐藏webView缩放按钮
        webSettings.setJavaScriptEnabled(true); // 设置支持javascript脚本
        webSettings.setAllowFileAccess(true); // 允许访问文件
        webSettings.setBuiltInZoomControls(false); // 设置显示缩放按钮
        webSettings.setSupportZoom(false); // 支持缩放
        webSettings.setBlockNetworkImage(true);
        //自适应屏幕
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setDomStorageEnabled(true); // 开启 DOM storage API 功能
        webSettings.setDatabaseEnabled(true); //开启 database storage API 功能
        webSettings.setAppCacheEnabled(true); //开启 Application Caches 功能
        webSettings.setDefaultTextEncodingName("UTF-8");
        webSettings.setDefaultFontSize(18);

        // NOTICE: don't use js op img
        webSettings.setBlockNetworkImage(true);

        wvHomeDetailIntroduce.addJavascriptInterface(new JavascriptInterface(this), "htmlCallback");
        wvHomeDetailIntroduce.setWebViewClient(new WebViewClient() {
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                // NOTICE: don't use js op img
                webSettings.setBlockNetworkImage(false);
            }
        });
    }

    private String getInsertJavaScript() {
        // logic:
        // 1. 将 origin_src 中的内容保存到 href 属性中
        //    将 src 设置为"点击图片加载"
        // 2. 分别设置点击和加载错误事件
        // 3. 用户点击时，将 src 设置为空白界面，并监听 onload
        //    onload 时替换掉 src 为真正的图片地址，清空 href 和 onload
        //
        return "<script>(function(){" +
//                "var images = document.getElementsByTagName(\"img\"); " +
//                "for(var i=0; i<images.length; i++) {\n" +
//                "    //images[i].href=images[i].getAttribute(\"src\");\n" +
//                "    //images[i].src=\"./article_image_click_to_load.png\";\n" +
//                "    images[i].onclick = function() {\n" +
//                "        if (this.href == \"\")\n" +
//                "            window.htmlCallback.openImage(this.src);\n" +
//                "        else {\n" +
//                "            this.onload = function() {\n" +
//                "                this.src = this.href;\n" +
//                "                this.href = \"\";\n" +
//                "                this.onload = null;\n" +
//                "            };\n" +
//                "            this.src = \"./article_image_empty.png\";\n" +
//                "        }\n" +
//                "    };\n" +
//                "    images[i].onerror = function() {\n" +
//                "        this.href = this.src;\n" +
//                "        this.src = \"./article_image_error.png\";\n" +
//                "    };\n" +
//                "}" +
                "var as = document.getElementsByTagName(\"a\");\n" +
                "for (var j=0; j<as.length; j++) {\n" +
                "    as[j].href=\"\"" +
                "    as[j].onclick = function() {\n" +
//                "        window.htmlCallback.openHref(this.href);\n" +
//                "        return false;\n" +
                "    }\n" +
                "}" +
                "})()</script>";
    }

    private String getHtmlData(String bodyHTML) {
        String head = "<head>" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
                "<style>" +
                "   img{max-width: 100%; width:auto; height:auto;margin:16px 0 16px 0;} \n" +
                "   body{padding: 0 10 0 10}\n" +
                "   .via-college-article-content {word-wrap: break-word; word-break}" +
                "</style>" +
                "</head>";

        // replace for "click to load"
        String content = bodyHTML;//bodyHTML.replaceAll("src=\"", "origin_src=\"");

        return "<html>" + head + "<body><div class=\"via-college-article-content\">" + content
                + getInsertJavaScript() + "</div></body></html>";
    }

    private void renderWebView(String content) {
        // file:///android_asset 用于支持点击加载图片部分
        if (Build.VERSION.SDK_INT >= 19) {
            wvHomeDetailIntroduce.loadDataWithBaseURL("file:///android_asset/", getHtmlData(content),
                    "text/html; charset=UTF-8", null, "");
        } else {
            wvHomeDetailIntroduce.loadDataWithBaseURL("file:///android_asset/", getHtmlData(content),
                    "text/html", null, null);
        }
    }
}
